IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_TemplateAdd]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_TemplateAdd]
GO
CREATE procedure [dbo].[cms_sp_TemplateAdd]
(
	@TemplateId int = null output,
	@SiteId int = null,
	@SiteGroupId int = null,
	@TemplateName nvarchar(250),
	@TemplateUrl nvarchar(250),
	@TemplateTypeKey int,
	@IsDefault bit,
	@TemplateRegions varchar(8000) = null,
	@TemplareRegionDelimiter nvarchar(5) = null,
	@CreatedBy int,
	@DateCreated datetime,
	@DefaultRegionId int = null
)
as
if @IsDefault = 1
begin
	update dbo.Templates
		set IsDefault = 0
end
insert into [dbo].[Templates]
(
SiteId,
SiteGroupId,
TemplateName,
TemplateUrl,
TemplateTypeKey,
IsDefault,
CreatedBy,
DateCreated,
DefaultRegionId
)
values
(
@SiteId,
@SiteGroupId,
@TemplateName,
@TemplateUrl,
@TemplateTypeKey,
@IsDefault,
@CreatedBy,
@DateCreated,
@DefaultRegionId
)
set @TemplateId = SCOPE_IDENTITY()
if @TemplareRegionDelimiter = null
begin
	set @TemplareRegionDelimiter = ';'
end
if @TemplateRegions is not null
begin
	insert into dbo.TemplateRegions
	(
	TemplateId,
	TemplateRegionName
	)
	select 	
		@TemplateId,
		tmp.part	
	from dbo.cms_udf_SplitString(@TemplateRegions, @TemplareRegionDelimiter) as tmp
end
return @TemplateId


GO

